package com.random.fox.whatspay.ui;

import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.random.fox.whatspay.AppContext;
import com.random.fox.whatspay.R;
import com.random.fox.whatspay.bean.Account;
import com.random.fox.whatspay.greendao.dao.AccountDao;

import java.util.List;

/**
 * Created by 渠 on 2014/11/8.
 */
public class AccountFragment extends BaseFragment {
    private GridView gridView;
    private AppContext appContext;
    private List<Account> accounts;
    private AccountDao accountDao;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        host = inflater.inflate(R.layout.account_frame,null);
        return host;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        appContext = (AppContext) mainAty.getApplicationContext();
        accountDao = appContext.getAccountDao();
        initView();
        initData();
    }

    @Override
    void initView() {
        gridView = (GridView) findViewById(R.id.gv_account_display);
    }

    @Override
    void initData() {
        //获取到所有的用户
        accounts = accountDao.loadAll();
        if (accounts!=null){
            gridView.setAdapter(new AccountAdapter(mainAty));
        }
    }


    private class AccountAdapter extends BaseAdapter{
        private Context mContext;
        public AccountAdapter(Context context){
            mContext = context;
        }

        @Override
        public int getCount() {
            return accounts.size();
        }

        @Override
        public Account getItem(int position) {
            return accounts.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final TextView textView = new TextView(mContext);
            textView.setText(getItem(position).getName());
            textView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    accountDao.deleteInTx(getItem(position));
                    accounts.remove(position);
                    notifyDataSetChanged();
                    return false;
                }
            });
            return textView;
        }
    }
}
